package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Voice;
import com.itheima.service.mongo.VoiceService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Random;

@Service
public class VoiceServiceImpl implements VoiceService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveVoice(Voice voice) {
        // 保存数据到Mongo表中
        mongoTemplate.save(voice);
    }

    @Override
    public Voice findVoice(Long userId) {

        // 构造条件 条件为表中的userId字段不等于登录用户userId  (防止查询到自己)
        Query query = new Query(Criteria.where("userId").ne(userId));

        // 查询到表中的所有用户 除了自己 返回到一个list中
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);

        // 得到集合的长度
        int size = voiceList.size();

        // 从list中查询随机一个人的数据
        Voice voice = voiceList.get(new Random().nextInt(size));
        // 返回前台
        return voice;
    }
}
